package com.zlzlib.liblayoutmanager;

import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

/**
 * @Desc:
 * @Copyright:
 * @DateTime: 2021/8/11 11:30
 * @Author zlz
 * @Version 1.0
 */
public class ScrollUtils {

    /**
     * 滚动到当前下标targetPosition的子视图的位置
     *
     * @param recyclerView
     * @param scrollLayoutManager
     * @param targetPosition
     */
    public static void smoothScrollToPosition(RecyclerView recyclerView, BaseLayoutManager scrollLayoutManager, int targetPosition) {
        final int delta = scrollLayoutManager.getOffsetToPosition(targetPosition);
        smoothScrollToOffset(recyclerView, scrollLayoutManager, delta);
    }

    /**
     * 滚动到 targetView 的位置
     *
     * @param recyclerView
     * @param targetView
     */
    public static void smoothScrollToTargetView(RecyclerView recyclerView, View targetView) {
        final RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (!(layoutManager instanceof BaseLayoutManager)) return;
        final int targetPosition = ((BaseLayoutManager) layoutManager).getLayoutPositionOfView(targetView);
        smoothScrollToPosition(recyclerView, (BaseLayoutManager) layoutManager, targetPosition);
    }

    /**
     * 滚动到 Offset的位置
     *
     * @param recyclerView
     * @param scrollLayoutManager
     * @param Offset
     */
    public static void smoothScrollToOffset(RecyclerView recyclerView, BaseLayoutManager scrollLayoutManager, int Offset) {
        if (scrollLayoutManager.getOrientation() == scrollLayoutManager.VERTICAL) {
            recyclerView.smoothScrollBy(0, Offset);
        } else {
            recyclerView.smoothScrollBy(Offset, 0);
        }
    }
}
